package edu.fpa.day0720;

public class SetLinkedList4{
    Node first;
    Node last;
    int size;

    public void add(Object obj){
        Node node = new Node(obj);
        if(size==0) {
            first = node;
            last = node;
            size++;
        }else {
            last.next = node;
            node.next = null;
            node.previous = last;
            last = node;
            size++;
        }
    }
    public Object get(int index) {
        if(index<0||index>size-1) {
            throw new RuntimeException("索引范围异常："+index);
        }
        Node node = getNode(index);

        return node != null?node.element:null;
    }
    public Node getNode(int index) {
        Node n = null;
        if(index<(size-1)>>1) {
            n = first;
            for(int i=0;i<index;i++) {
                Node n1 = n.next;
                n=n1;
            }}else {
            n = last;
            for(int i = size-1;i>index;i--) {
                Node n1 = n.previous;
                n= n1;
            }
        }
        return n;
    }
    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        Node node1  = first;
        do{
            Node node2  = node1;
            sb.append(node1.element+",");
            node1 = node2.next;
        }while(node1!=null);
        sb.setCharAt(sb.length()-1,']');
        return sb.toString();
    }
    public void remove(int index) {
        if(index<0||index>size-1) {
            throw new RuntimeException("索引范围异常："+index);
        }
        Node node = getNode(index);
        if(node!=null)
        {
            Node node1 = node.previous;
            Node node2 = node.next;
            if(node1!=null){
                node1.next = node2;
            }else {
                first = node2;
            }
            if(node2!=null) {
                node2.previous = node1;
            }else {
                last = node1;
            }
            size--;
        }

    }
    public static void main(String[] args){
        SetLinkedList4 s = new SetLinkedList4();
        s.add("a");
        s.add("b");
        s.add("c");
        System.out.println(s);
        System.out.println(s.get(1));
        s.add("d");
        s.add("f");
        System.out.println(s);
        s.remove(3);
        System.out.println(s);
        s.remove(0);
        System.out.println(s);
        s.remove(2);
        System.out.println(s);
    }
}
